package top.huhuiyu.springboot3.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * 加密相关工具
 *
 * @author 胡辉煜
 */
public class EncryptorUtils {
  public static final Random RANDOM = new Random();
  public static final String RANDOM_STRING = "abcdefghijklmnopqrstuvwxyz0123456789";
  public static final int MIN_LENGTH = 5;
  public static final int MAX_LENGTH = 50;
  private static final String MAIN_ENCRYPTOR_PASSWORD = "api.huhuiyu.top.password";

  /**
   * 生成指定长度的随机字符串
   *
   * @param length 随机字符串长度
   * @return 指定长度的随机字符串
   */
  public static String randString(int length) {
    length = length < MIN_LENGTH || length > MAX_LENGTH ? MIN_LENGTH : length;
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < length; i++) {
      builder.append(RANDOM_STRING.charAt(RANDOM.nextInt(RANDOM_STRING.length())));
    }
    return builder.toString();
  }

  /**
   * 生成长度为5的随机字符串
   *
   * @return 随机字符串
   */
  public static String randString() {
    return randString(MIN_LENGTH);
  }

  /**
   * md5加密
   *
   * @param info 要md5加密的字符
   * @return md5加密的结果
   */
  public static String md5(String info) {
    return StringUtils.hasText(info) ? DigestUtils.md5DigestAsHex(info.getBytes(StandardCharsets.UTF_8)) : "";
  }

  /**
   * 带盐的md5加密
   *
   * @param info 要md5加密的字符
   * @param salt 加密盐
   * @return md5加密的结果
   */
  public static String saltMd5(String info, String salt) {
    if (!StringUtils.hasText(info)) {
      return "";
    }
    if (!StringUtils.hasText(salt)) {
      salt = "";
    }
    return DigestUtils.md5DigestAsHex((info + salt).getBytes(StandardCharsets.UTF_8));
  }

}
